<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>icf</title>

    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
        content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <link rel="stylesheet" href="/public/layui/admin/layui/css/layui.css" media="all">
    <link rel="stylesheet" href="/public/layui/admin/style/admin.css" media="all">
</head>

<body>

    <div class="layui-fluid">
        <div class="layui-card">
            <div class="layui-card-header">Product</div>
            <div class="layui-card-body" style="padding: 15px;">
                <form class="layui-form" action="" lay-filter="component-form-group">
                    {% if data.detail.Id %}
                    <input name="id" id="id" type="hidden" value="{{ data.detail.Id }}" />
                    {% endif %}

                    <div class="layui-tab layui-tab-card">

                        <ul class="layui-tab-title">
                            <li class="layui-this">基础信息</li>
                            <li>规格信息</li>
                            <li>商品详情</li>


                        </ul>


                        <div class="layui-tab-content">
                            <div class="layui-tab-item layui-show">

                                <div class="layui-form-item">
                                    <label class="layui-form-label">销售的APP套餐</label>
                                    <div class="layui-input-block">
                                        <input type="hidden" name="app_suit_code" id="app_suit_code" value="{{data.detail.AppSuitCode}}">
                                        <select name="app_suit_code" id="app_suit_code" lay-verify="required"  {% if data.detail.Id %}  {% endif %}>
                                            <option value="">请选择要销售的APP套餐</option>
                                            {% for item in data.appsuit %}
                                            <option value={{item.AppSuitCode}}  {% if item.AppSuitCode == data.detail.AppSuitCode %}selected{% endif %}>微应用套餐标识码:<{{item.AppSuitCode}}>  |  名称：<{{item.AppSuitName}}>></option>
                                            {% endfor %}
                                        </select>

                                    </div>
                                </div>

                                <div class="layui-form-item">
                                    <label class="layui-form-label">商品名称</label>
                                    <div class="layui-input-block">
                                        <input type="text" id="product_name" name="product_name"
                                            value="{{ data.detail.ProductName }}" lay-verify="title" autocomplete="off"
                                            placeholder="" class="layui-input">
                                    </div>
                                </div>



                                <div class="layui-form-item">
                                    <label class="layui-form-label">商品图片</label>
                                    <div class="layui-input-block">

                                        <input type="hidden" id="defaultImage" name="defaultImage"
                                            value="{{ data.detail.DefaultImage }}" />
                                        <div class="layui-upload-drag" id="upload-drag">
                                            <i class="layui-icon"></i>
                                            <p>点击上传图片</p>
                                            <img id="img-upload" src="{{ data.detail.DefaultImage }}"
                                                style="width: 200px">
                                        </div>


                                    </div>
                                </div>



                                <div class="layui-form-item">
                                    <label class="layui-form-label">视频</label>
                                    <div class="layui-input-block">
                                        <input type="hidden" id="video" name="video" value="{{ data.detail.Video }}" />
                                        <div class="layui-upload-drag" id="upload-video-drag">
                                            <i class="layui-icon"></i>
                                            <p>点击上传视频</p>

                                            <video width="320" height="240" src="{{ data.detail.Video }}"
                                                id="product_video" controls="controls">'
                                                <!-- <source id="video_source" src="{{ data.detail.Video }}"
                                                    type="video/mp4" /> -->
                                                <!-- <object id="video_object" data="{{ data.detail.Video }}" width="320"
                                                    height="240">
                                                    <embed id="video_embed" width="320" height="240"
                                                        src="{{ data.detail.Video }}" />
                                                </object> -->
                                            </video>

                                            <!-- <img id="img-upload" src="{{ data.detail.Video }}" style="width: 100%"> -->
                                        </div>
                                    </div>
                                </div>



                                <div class="layui-form-item">
                                    <label class="layui-form-label">运费</label>
                                    <div class="layui-input-block">
                                        <input type="number" id="postage" name="postage"
                                            value="{{ data.detail.Postage }}" lay-verify="title" step="0.01"
                                            placeholder="" class="layui-input">
                                    </div>
                                </div>

                                <div class="layui-form-item">
                                    <label class="layui-form-label">销售状态</label>
                                    <div class="layui-input-block">
                                        <!-- <input type="hidden" id="if_sale_value" name="if_sale_value" value="{{data.detail.IfSale}}" > -->
                                        <input type="checkbox" name="if_sale" id="if_sale" lay-skin="switch" value="1"
                                               {% if data.detail.IfSale == 1 %}checked{% endif %}  lay-text="销售中|下架">
                                    </div>
                                </div>






                            </div>

                            <div class="layui-tab-item">
                                <!-- 表格 -->

                                <script type="text/html" id="data-table-filter">
                                    <div class="layui-btn-container">
                                        <button class="layui-btn layui-btn-sm" lay-event="add">添加</button>
                                    </div>
                                </script>


                                <table class="layui-hide" id="data-table" lay-filter="data-table"></table>

                                <!-- 操作工具栏 -->
                                <script type="text/html" id="data-table-toolbar">
                                    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
                                </script>

                            </div>


                            <div class="layui-tab-item">

                                <div class="layui-form-item">

                                    <!-- <input type="hidden" id="field_desc" name="field_desc"
                                        value="{{ data.detail.Description }}" lay-verify="title" autocomplete="off"
                                        placeholder="" class="layui-input"> -->

                                    <script id="editorDesc" type="text/plain" style="height:250px; z-index:-10000;">
                                    </script>


                                </div>

                            </div>

                        </div>


                    </div>




                    <div class="layui-form-item layui-layout-admin">
                        <div class="layui-input-block">
                            <div class="layui-footer" style="left: 0;">
                                <button class="layui-btn" lay-submit="" lay-filter="edit-submit">提交</button>
                                <a href="javascript:goBack()" class="layui-btn layui-btn-primary">返回</a>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>


    <script src="/public/layui/admin/layui/layui.js"></script>

    <script src="/public/build/js/base64.js"></script>
    <script src="/public/vendors/ueditor/ueditor.config.js"></script>
    <script src="/public/vendors/ueditor/ueditor.all.min.js"></script>

    <script>
        layui.config({
            base: '/public/layui/admin/' //静态资源所在路径
        }).extend({
            index: 'lib/index' //主入口模块
        }).use(['index', 'table', 'form', 'laydate', 'jquery', 'upload', 'element'], function () {
            var $ = layui.$,
                admin = layui.admin,
                element = layui.element,
                layer = layui.layer,
                laydate = layui.laydate,
                form = layui.form;
            // var element = layui.element;
            // //一些事件监听
            // element.on('tab(demo)', function (data) {
            //     console.log(data);
            // });

            var product = {};
            var productSpecs = new Array();

            var table = layui.table;
            table.render({
                elem: '#data-table',
                //url: '/admin/AppProductSpec/GetProductSpecListJson?product_id={{data.detail.Id}}&appid={{data.Who.MiniAppId}}&tid={{data.Who.TenantId}}',
                cellMinWidth: 80, //全局定义常规单元格的最小宽度，layui 2.2.1 新增
                toolbar: '#data-table-filter',
                data: productSpecs,
                cols: [
                    [
                        //#TableJsonFields#
                        {
                            field: 'id',
                            title: 'id',
                            hide: true
                        },
                        {
                            field: 'spec_name',
                            title: '规格',
                            hide: false,
                            edit: 'text'
                        },
                        {
                            field: 'sell_price',
                            title: '售价',
                            hide: false,
                            edit: 'number'
                        },
                        {
                            field: 'stock',
                            title: '库存',
                            hide: false,
                            edit: 'number'
                        },
                        {
                            field: 'months',
                            title: '月数',
                            hide: false,
                            edit: 'number'
                        },
                        {
                            fixed: 'right',
                            title: '操作',
                            toolbar: '#data-table-toolbar',
                            width: 120
                        }
                    ]
                ],
                page: true
            });

            //监听行工具事件
            table.on('tool(data-table)', function (obj) {
                var data = obj.data;
                console.log('table on click');
                if (obj.event === 'del') {
                    // parent.layer.confirm('真的删除行么', function (index) {
                    //     obj.del();
                    //     layer.close(index);
                    // });

                    layer.confirm('真的删除行么', function (index) {
                        var oldData = table.cache["data-table"];
                        oldData.splice(oldData.findIndex(item=>item.id== obj.data.id),1);
                        table.reload('data-table', {
                            data: oldData
                        });
                        //obj.del();
                        layer.close(index);
                    });
                }
            });

            //头工具栏事件
            table.on('toolbar(data-table)', function (obj) {
                switch (obj.event) {
                    case 'add': {
                        addSpec();
                    }
                    break;
                };
            });


            form.render(null, 'component-form-group');
            laydate.render({
                elem: '#LAY-component-form-group-date'
            });

            /* 自定义验证规则 */
            form.verify({
                title: function (value) {
                    if (value.length < 0) {
                        return '请输入';
                    }
                },
                pass: [/(.+){6,12}$/, '密码必须6到12位'],
                content: function (value) {
                    layedit.sync(editIndex);
                }
            });

            // 文件上传
            var upload = layui.upload;
            upload.render({
                elem: '#upload-drag',
                url: '/admin/uploadalioss',
                accept: 'images',
                acceptMime: 'image/*',
                done: function (res) {
                    console.log(res)
                    $("#img-upload").attr("src", res.data.imgurl);
                    $('#defaultImage').val(res.data.imgurl);
                    // TODO: $("#prdminipic").val(res.data.imgurl);
                }
            });

            // 视频文件上传
            var videoUpload = layui.upload;
            videoUpload.render({
                elem: '#upload-video-drag',
                url: '/admin/uploadalioss',
                accept: 'video',
                acceptMime: 'video/*',
                done: function (res) {
                    console.log(res)

                    // var video = $("#product_video");

                    $("#product_video").attr("src", res.data.imgurl);
                    $("#video").val(res.data.imgurl);
                    //$("#video_object").attr("data", res.data.imgurl);
                    //$("#video_embed").attr("src", res.data.imgurl);
                    // TODO: $("#prdminipic").val(res.data.imgurl);
                }
            });

            // /* 监听提交 */
            form.on('submit(edit-submit)', function (data) {
                // parent.layer.alert(JSON.stringify(data.field), {
                //   title: '最终的提交信息'
                // })

                /*product.product_name = $("#product_name").val();
                product.Id = $("#id").val();
                //product.Id = product.Id|Number(product.Id);
                product.defaultImage = $("#defaultImage").val();
                product.video = $("#video").val();
                product.postage = Number($("#postage").val());
                if ($("#if_sale").is(":checked")) {
                    product.if_sale = 1;
                } else {
                    product.if_sale = 0;
                }
                //product.if_sale = $("#if_sale").is(":checked");
                product.shop_id = $("#shop_list").val();*/
                product = data.field
                let ue = UE.getEditor('editorDesc');
                //let str = ue.getContent();
                let arr = [];
                arr.push(ue.getContent());
                let finalstr = arr.join("");
                let base = new Base64();

                product.description = base.encode(finalstr);

                var speclist = table.cache["data-table"];

                if (speclist.length == 0) {
                    parent.layer.alert("规格信息不能为空", {
                        title: '提示 2 '
                    });
                    return;
                }
                product.speclist = [];
                speclist.forEach(element => {
                    var spec = {
                        "spec_name": element.spec_name,
                        "sell_price": Number(element.sell_price),
                        "stock": Number(element.stock),
                        "months": Number(element.months),
                        "id": element.id
                    };

                    product.speclist.push(spec);
                    //product.speclist.push(element);
                });
                //product.speclist = spec

                console.log(product);

                $.ajax({
                    type: "POST",
                    url: "/admin/AppProduct/editpage?appid={{data.Who.MiniAppId}}&tid={{data.Who.TenantId}}",
                    data: JSON.stringify(product),
                    async: true,
                    dataType: 'JSON',
                    contentType: 'application/json',
                    error: function (request) {
                        parent.layer.alert(JSON.stringify(request), {
                            title: '操作失败'
                        });
                    },
                    success: function (response) {
                        console.log(response);
                        //var rt = JSON.parse(response);
                        var rt = response
                        if (rt.code == 0) {
                            var index = parent.layer.getFrameIndex(window.name); //获取窗口索引
                            parent.layer.close(index);
                        } else {
                            parent.layer.alert(rt.msg, {
                                title: '操作失败'
                            });
                        }
                    }
                });
                return false;
            });

            function addSpec() {
                var oldData = table.cache["data-table"];
                var newspec = {
                    "spec_name": "",
                    "sell_price": 0,
                    "stock": 0,
                    "id": undefined
                };
                oldData.push(newspec);
                table.reload('data-table', {
                    data: oldData
                });
            }


            init();

            function init() {
                // 图文内容
                let description = '{{data.detail.Description}}';
                console.log("================2", description);
                let base = new Base64();
                let content2 = base.decode(description);

                let ue2 = UE.getEditor('editorDesc');
                //对编辑器的操作最好在编辑器ready之后再做
                ue2.addListener("ready", function () {
                    console.log("content2:", content2);
                    ue2.setContent(content2);
                });



                var product_id = $("#id").val();

                $.ajax({
                    type: "Get",
                    url: '/admin/AppProductSpec/GetProductSpecListJson?product_id={{data.detail.Id}}&appid={{data.Who.MiniAppId}}&tid={{data.Who.TenantId}}',
                    async: true,
                    error: function (request) {
                        parent.layer.alert(JSON.stringify(request), {
                            title: '操作失败'
                        });
                    },
                    success: function (response) {
                        productSpecs = response.data;
                        // var oldData = table.cache["data-table"];
                        // productSpecs.forEach(element => {
                        //     var newspec = {
                        //         "spec_name": element.spec_name,
                        //         "sell_price": Number(element.sell_price),
                        //         "stock": Number(element.stock),
                        //         "id": Number(element.id)
                        //     };
                        //     oldData.push(newspec);
                        // });
                        // table.reload('data-table', {
                        //     data: oldData
                        // });
                        table.reload('data-table', {
                            data: productSpecs
                        });

                        if (!product_id) {
                            addSpec();
                        }
                    }
                });




                // var if_sale = $("#if_sale_value").val()
                // if(if_sale && if_sale == 1){
                //     $("#if_sale").is(":checked") = true;
                // }else{
                //     $("#if_sale").is(":checked") = false;
                // }

            }

            /* 监听指定开关
            form.on('switch(component-form-switchTest)', function(data){
              layer.msg('开关checked：'+ (this.checked ? 'true' : 'false'), {
                offset: '6px'
              });
              layer.tips('温馨提示：请注意开关状态的文字可以随意定义，而不仅仅是ON|OFF', data.othis)
            });*/
        });

        // 页面返回上一页面
        function goBack() {
            var index = parent.layer.getFrameIndex(window.name); //获取窗口索引
            parent.layer.close(index);
        };
    </script>
</body>

</html>